package nbcp.web.product

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import nbcp.base.comm.*
import org.springframework.web.bind.annotation.RestController
import nbcp.base.extend.*
import nbcp.comm.JsonpMapping
import nbcp.db.KeyValueString
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.ProductSkuStockPrice

/**
 * Created by Cy on 17-4-1.
 */

@Api(description = "商品信息", tags = arrayOf("ProductInfo"))
@RestController
@JsonpMapping("/info/product")
class ProductInfo_Sku_Controller {


    data class SkuResultModel(
            var skuDefines: MutableList<KeyValueString> = mutableListOf(),
            var skuStockPrice: MutableList<ProductSkuStockPrice> = mutableListOf()
//            var activityType: ActivityTypeEnum = ActivityTypeEnum.Empty
    )

    //  xx/productInfo/listSku
    @ApiOperation("(编辑时)获取skus属性")
    @JsonpMapping("/listProductSkuInfo")
    fun listProductSkuInfo(productId: String): ApiResult<SkuResultModel> {
        var ret = ApiResult.of(data = SkuResultModel());

        //根据productId查询出对应的商品
        val productInfo = mor.info.productInfo.queryById(productId)
                .select(mor.info.productInfo.skuDefines.toString())
                .select(mor.info.productInfo.skuStockPrice.toString())
                .toEntity();

        if (productInfo == null) {
            //logger.error("商品ID为" + productId + "的没有获取到sku")
            ret.msg = "找不到商品信息";
            return ret;
        }
        //获取到sku
        //放入到ListResult中
        ret.data!!.skuDefines = productInfo.skuDefines;
        ret.data!!.skuStockPrice = productInfo.skuStockPrice;
//        ret.data!!.activityType = productInfo.activityType;

        return ret;
    }

    //  xx/productInfo/parameters
    @ApiOperation("添加SkuDefine")
    @JsonpMapping("/addSkuDefine")
    fun addSkuDefine(productId: String, skuKey: String, skuValue: String): JsonResult {
        var skuValue = skuValue.replace("，",",");

        var productInfo = mor.info.productInfo.queryById(productId).toEntity();
        if (productInfo == null) {
            return JsonResult("找不到商品信息")
        }

        productInfo.skuDefines.add(KeyValueString(skuKey, skuValue))
        productInfo.skuStockPrice = syncSkuStock(productInfo.guidePrice, productInfo.skuDefines, productInfo.skuStockPrice);


        //更新modify表parameters
        mor.info.productInfo
                .updateById(productId)
                .set(mor.info.productInfo.skuDefines.toString(), productInfo.skuDefines)
                .set(mor.info.productInfo.skuStockPrice.toString(), productInfo.skuStockPrice)
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult("添加parameters属性失败")
        }

        //返回执行查询sku列表数据
        return JsonResult();
    }

    //  xx/productInfo/saveSku
    @ApiOperation("修改SkuDefine")
    @JsonpMapping("/saveSkuDefine")
    fun saveSkuDefine(productId: String, index: Int, skuKey: String, skuValue: String): JsonResult {
        if (index < 0) {
            return JsonResult("索引非法")
        }
        var productInfo = mor.info.productInfo.queryById(productId).toEntity();
        if (productInfo == null) {
            return JsonResult("找不到商品信息")
        }

        if (index >= productInfo.skuDefines.size) {
            return JsonResult("索引非法")
        }
        var skuValue = skuValue.replace("，",",");

        productInfo.skuDefines[index] = KeyValueString(skuKey, skuValue)
        productInfo.skuStockPrice = syncSkuStock(productInfo.guidePrice, productInfo.skuDefines, productInfo.skuStockPrice);

        mor.info.productInfo
                .updateById(productId)
                .set(mor.info.productInfo.skuDefines.toString(), productInfo.skuDefines)
                .set(mor.info.productInfo.skuStockPrice.toString(), productInfo.skuStockPrice)
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult("修改SkuDefine失败")
        }

        return JsonResult();
    }


    //  xx/productInfo/delSku
    @ApiOperation("删除SkuDefine")
    @JsonpMapping("/delSkuDefine")
    fun delSkuDefine(productId: String, index: Int): JsonResult {
        if (index < 0) return JsonResult("索引非法")

        var productInfo = mor.info.productInfo.queryById(productId).toEntity();
        if (productInfo == null) {
            return JsonResult("找不到商品信息")
        }

        if (index >= productInfo.skuDefines.size) {
            return JsonResult("索引非法")
        }

        productInfo.skuDefines.removeAt(index);

        productInfo.skuStockPrice = syncSkuStock(productInfo.guidePrice, productInfo.skuDefines, productInfo.skuStockPrice);

        mor.info.productInfo
                .updateById(productId)
                .set(mor.info.productInfo.skuDefines.toString(), productInfo.skuDefines)
                .set(mor.info.productInfo.skuStockPrice.toString(), productInfo.skuStockPrice)
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult("删除sku属性失败")
        }

        return JsonResult()
    }


    @ApiOperation("保存Sku库存价格")
    @JsonpMapping("/saveSkuStock")
    fun saveSkuStock(productId: String, skuStockPrice: MutableList<ProductSkuStockPrice>): JsonResult {
        mor.info.productInfo.updateById(productId)
                .set(mor.info.productInfo.skuStockPrice.toString(), skuStockPrice)
                .exec();

        if (mor.affectRowCount == 0) {
            return JsonResult("更新Sku库存失败或数据没有改变")
        }

        return JsonResult();
    }


    /**
     * 如:  [3,2] , 4  ,返回:  [1,1]
     * @param bitValue [3,2] 表示第一个数组是3个元素,第2个数组是2个元素
     * @param index 获取第几位.
     * @return 返回各个位的索引.
     */
    fun getSequenceIndex(bitValues: Array<Int>, index: Int): Array<Int> {
        var ret = mutableListOf<Int>();
        var index = index;
        for (i in bitValues.size - 1 downTo 0) {
            var value = bitValues[i];
            ret.add(index % value);

            index = index / value;
        }

        return ret.reversed().toTypedArray()
    }

    /**
     * @param skuArrayData : [ [a,b,c] ,[东,西] ]
     */
    fun getSkuItem(skuValues: Array<Array<String>>, index: Int): Array<String> {
        if (index < 0) return arrayOf()

        //[ 3,2 ]
        var indexes = getSequenceIndex(skuValues.map { it.size }.toTypedArray(), index);

        var ret = indexes.mapIndexed { index, it ->
            skuValues[index][it]
        }.toTypedArray();

        println(index.toString() + ":" + indexes.ToJson() + ":" + ret.joinToString(","))
        return ret;
    }

    //返回所有组合.
    fun getAllSkuUnits(skuDefines: MutableList<KeyValueString>): MutableList<ProductSkuStockPrice> {
        var skuValues = skuDefines.map { it.value.split(",").toTypedArray() }.toTypedArray();

        var ret = mutableListOf<ProductSkuStockPrice>();
        var total = 1;
        skuValues.map { it.size }.forEach { total = total * it }

        for (i in 0..total - 1) {
            ret.add(ProductSkuStockPrice(getSkuItem(skuValues, i).joinToString(","), 0, "",0))
        }

        return ret;
    }

    fun skuEqual(sku1: String, sku2: String): Boolean {
        return sku1.split(",").EqualArrayContent(sku2.split(","))
    }

    fun syncSkuStock(salePrice: Int, skuDefines: MutableList<KeyValueString>, skuStockPrice: MutableList<ProductSkuStockPrice>): MutableList<ProductSkuStockPrice> {
        var skus = getAllSkuUnits(skuDefines);
        skus.forEach { sku ->
            var dbOne = skuStockPrice.firstOrNull { skuEqual(it.skuDefine, sku.skuDefine) }
            if (dbOne != null) {
                sku.stock = dbOne.stock
                sku.salePrice = dbOne.salePrice
                sku.activityPrice = dbOne.activityPrice
            } else {
                sku.salePrice = salePrice
                sku.activityPrice = salePrice
            }
        }

        return skus;
    }
}